package com.zmm.member.controller;

import com.zmm.common.base.model.Result;
import com.zmm.common.base.model.ResultCode;
import com.zmm.common.constant.NumberConstant;
import com.zmm.common.enums.AccountType;
import com.zmm.common.enums.RegistryMethodEnums;
import com.zmm.common.exception.handle.BusinessException;
import com.zmm.member.model.Customer;
import com.zmm.member.service.CustomerService;
import com.zmm.member.service.LoginService;
import com.zmm.member.service.RegistryService;
import com.zmm.member.submit.vo.RegisterLoginVo;
import com.zmm.util.auth.model.Token;
import com.zmm.util.convert.StringUtil;
import com.zmm.util.ip.IpUtil;
import com.zmm.util.verify.BindingResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @author 900045
 * @description:
 * @name CustomerLoginController
 * @date By 2021-08-06 10:35:01
 */
@Controller
@Slf4j
@RequestMapping("/customer")
public class CustomerLoginController extends LoginController {


	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private LoginService loginService;
	
	@Autowired
	private RegistryService registryService;


	/**
	 * 去到用户登录的页面
	 * @author: 900045
	 * @date: 2021-08-06 11:19:27
	 * @throws 
	 * @return: java.lang.String
	 **/
	@RequestMapping(value = "/to/login",method = RequestMethod.GET)
	public String toAddCustomer(){
		return "login_customer";
	}
	
	/**
	 * 用户登录/注册
	 * @author: 900045
	 * @date: 2021-08-06 11:07:10
	 * @throws 
	 * @param registerLoginVo: 
	 * @param result: 
	 * @param request: 
	 * @return: com.zmm.common.base.model.Result
	 **/
	@ResponseBody
	@PostMapping(value = "/login")
	public Result customerRegisterOrLogin(@Valid RegisterLoginVo registerLoginVo, BindingResult result, HttpServletRequest request) {
		// step1.表达校验
		if (result.hasErrors()){
			return BindingResultUtil.paramVerify(result);
		}
		String ip = IpUtil.getIpAddress(request);
		// step2.判断是 手机号/密码 登录
		if (StringUtil.isNotBlank(registerLoginVo.getPassword())){
			// step2.1 账户密码登录
			Customer customer;
			try {
				customer = loginService.doLogin(registerLoginVo.getPhone(), registerLoginVo.getPassword(), ip);
			} catch (BusinessException e) {
				return Result.error(e.getCode(),e.getMessage());
			}
			Token token = createToken(ip, customer);
			log.warn("DO-LOGIN-CODE:{} == {}", registerLoginVo.getPhone(), token);
			return Result.ok().setData(token);
		} else if (StringUtil.isNotBlank(registerLoginVo.getVerifyCode())){
			// step2.2 手机验证码登录
			
			Customer customerExist = customerService.findOneCustomerByPhone(registerLoginVo.getPhone());

			if (ObjectUtils.isEmpty(customerExist)) {
				// step2.2.1不存在则去 注册
				try {
					// type = 1  注册
					Customer customer = registryService.registryByPhone(registerLoginVo.getPhone(), registerLoginVo.getPassword(),
							registerLoginVo.getVerifyCode(), NumberConstant.ONE, registerLoginVo.getIp(),
							RegistryMethodEnums.VERIFY_CODE, ip, null,null);
					if (ObjectUtils.isEmpty(customer)) {
						return Result.error(ResultCode.USER_REGISTRY_EXPIRE);
					}
					Token token = getToken(customer,AccountType.MAIN_ACCOUNT.getCode());
					return Result.ok().setData(token);
				} catch (BusinessException e) {
					log.error("customerRegisterOrLogin 此处有异常[{}]",e.getMessage());
					return Result.error(e.getCode(),e.getMessage());
				}
			} else {
				// step2.2.2 登录
				if (!loginService.captchaSmsVerifyCode(registerLoginVo.getPhone(), NumberConstant.TWO, registerLoginVo.getVerifyCode())) {
					// 验证失败
					return Result.error(ResultCode.USER_VERIFY_CODE_EXPIRE);
				}
				customerService.modifyLoginIpByCustomerId(ip,customerExist.getCustomerId());
				Token token = createToken(ip, customerExist);
				// 成功 返回 token
				return  Result.ok().setData(token);
			}
		}
		// step2.3 不满足 提示错误
		return Result.error(ResultCode.METHOD_CALL_PARAMETER_ERROR);
	}

	/**
	 * 为用户创建 token
	 * @author: 900045
	 * @date: 2021-08-06 17:15:59
	 * @throws 
	 * @param ip: 
	 * @param customerExist: 
	 * @return: com.zmm.util.auth.model.Token
	 **/
	private Token createToken(String ip, Customer customerExist) {
		Integer accountType = AccountType.SUB_ACCOUNT.getCode();
		if (customerExist.getLoginIp().equals(ip)) {
			accountType = AccountType.MAIN_ACCOUNT.getCode();
		}
		customerExist.setLoginIp(ip);
		return getToken(customerExist, accountType);
	}


	/**
	 * 用户退出
	 * @author: 900045
	 * @date: 2021-08-06 16:55:39
	 * @throws 
	 * @return: com.zmm.common.base.model.Result
	 **/
	@GetMapping(value = "/logout")
	@ResponseBody
	public Result logout() {
		this.doLogout();
		return Result.ok(ResultCode.SUCCESS);
	}
}
